#include "PCF8574.h"

#include "i2c.h"
#include "delay.h"
#define uchar unsigned char

unsigned char  LCD_data;

void PCF8574_write(unsigned char data_wr)
{
	IIC_Start();
	IIC_WriteByte((0x27<<1)|0);
	IIC_testack();
	IIC_WriteByte(date);
	IIC_testack();
	IIC_Stop();
	
	i2c_cmd_handle_t cmd = i2c_cmd_link_create();
    i2c_master_start(cmd);
    i2c_master_write_byte(cmd, ( 0x27 << 1 ) | WRITE_BIT, 1);
    i2c_master_write(cmd, data_wr, size, ACK_CHECK_EN);
    i2c_master_stop(cmd);
    esp_err_t ret = i2c_master_cmd_begin(i2c_num, cmd, 1000 / portTICK_RATE_MS);
    i2c_cmd_link_delete(cmd);
} 

void LCD_enable_write(){
	LCD_data|=(1<<(3-1));
	PCF8574_write(LCD_data|0x08);	
	Delayus(2); 	
	LCD_data&=~(1<<(3-1));//E=0;
	PCF8574_write(LCD_data|0x08); 	
	DelayMs(15);	//默认开始状态为关使能端，见时序图 选择状态为 写 

}

void LCD_write_com(unsigned char command)
{ 
	LCD_data&=~(1<<(1-1));//RS=0;  
	LCD_data&=~(1<<(2-1));//RW=0;
	PCF8574_write(LCD_data);
	
	LCD_data&=0X0f; //清高四位
	LCD_data|=command & 0xf0; //写高四位
	PCF8574_write(LCD_data|0x08);
	LCD_enable_write();

	command=command<<4; //低四位移到高四位
	LCD_data&=0x0f; //清高四位
	LCD_data|=command&0xf0;//写低四位
	PCF8574_write(LCD_data|0x08);
	LCD_enable_write();
} 

void LCD_write_date(unsigned char value) 
{
	LCD_data|=(1<<(1-1));//RS=0;  
	LCD_data&=~(1<<(2-1));//RW=0;
	PCF8574_write(LCD_data|0x08);
	
	LCD_data&=0X0f; //清高四位
	LCD_data|=value & 0xf0; //写高四位
	PCF8574_write(LCD_data|0x08);
	LCD_enable_write();

	value=value<<4; //低四位移到高四位
	LCD_data&=0x0f; //清高四位
	LCD_data|=value&0xf0;//写低四位
	PCF8574_write(LCD_data);
	LCD_enable_write();
} 


void LCD_open() 
{
	LCD_write_com(0x28);
	LCD_write_com(0x28);
	LCD_enable_write();
	LCD_write_com(0x28);	DelayMs(15); 	//显示模式设置 0x28中高位2，设置4线。
	
	LCD_write_com(0x0c);	DelayMs(15);	//显示功能设置0x0f为开显示，显示光标，光标闪烁；0x0c为开显示，不显光标，光标不闪 
	
	LCD_write_com(0x06);	DelayMs(15);	//设置光标状态默认0x06,为读一个字符光标加1.

	LCD_write_com(0x01);	DelayMs(15);	//显示清屏，将上次的内容清除，默认为0x01. 
	
	LCD_write_com(0x02); 
} 


void LCD_write(unsigned char *str,int value,int lin) 
{
	uchar i=0;
    uchar code DDRAM[]={0x80,0xc0};
    LCD_write_com(DDRAM[lin-1]|value);
    while(str[i]&&i<16)
		LCD_write_date(str[i++]); 

} 
